package com.eurasia.assignment.controller;

import com.eurasia.assignment.domain.Assignment;
import com.eurasia.assignment.service.AssignmentService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/assignments") // 统一前缀，提高API的清晰度
public class AssignmentController {
    private final AssignmentService assignmentService;

    @GetMapping("/{id}")
    public ResponseEntity<Assignment> getAssignment(@PathVariable Long id) {
        return assignmentService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping
    public ResponseEntity<List<Assignment>> getAssignments() {
        return ResponseEntity.ok(assignmentService.findAll());
    }

    @PostMapping
    public ResponseEntity<Assignment> addAssignment(@RequestBody Assignment assignment) {
        Assignment createdAssignment = assignmentService.addAssignment(assignment);
        return new ResponseEntity<>(createdAssignment, HttpStatus.CREATED);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteAssignment(@PathVariable Long id) {
        if (assignmentService.deleteById(id)) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<Assignment> updateAssignment(@PathVariable Long id, @RequestBody Assignment assignment) {
        return assignmentService.findById(id)
                .map(existingAssignment -> {
                    Assignment updatedAssignment = assignmentService.updateAssignment(id, assignment);
                    return new ResponseEntity<>(updatedAssignment, HttpStatus.OK);
                })
                .orElse(ResponseEntity.notFound().build());
    }
}
